<script setup lang="ts">
import { ArrowRight } from "@element-plus/icons-vue";
import { resetPwd, getAgreement, loginOrRegisterAPI, sendSmsCodeAPI } from "~/api/user";
import { useUserStore } from "~/store/useUser";
import { onMounted, ref } from "vue";
import { encrypt } from "~/utils/func";
import { useSocketStore } from "~/store/useSocket";

useSeoMeta({
  title: "登录 - 技能猴子",
  ogTitle: "登录 - 技能猴子",
  description: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
  ogDescription: "技能猴子，找技能服务，我喜欢和技能人才直接聊",
});

const socketStore = useSocketStore();
const userStore = useUserStore();
const socket = computed(() => socketStore.socket);
const router = useRouter();
const route = useRoute();
const checked = ref(true);
const tabActive = ref(0);
const reserPwdStatus = ref(false);

onMounted(async () => {
  await userStore.logout();
  if (socket.value) {
    window.location.reload();
  }
});

const tapTabActive = (index) => {
  tabActive.value = index;
};
// 发送验证码
const sendStatus = ref(false);
const snedTime = ref(60);
const mobile = ref("");
const smsCode = ref("");
const timer = ref();
const sendSms = async () => {
  if (!mobile.value) {
    return ElMessage.warning("请输入手机号");
  }
  // 正则表达式
  if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
    return ElMessage.warning("请输入正确的手机号");
  }
  if (sendStatus.value || snedTime.value !== 60) return;
  sendStatus.value = true;
  try {
    // 使用新的短信接口
    const data = await sendSmsCodeAPI(mobile.value);
    if (data.code === 200) {
      ElMessage.success("发送成功");
    }
    timer.value = setInterval(() => {
      snedTime.value--;
      if (snedTime.value === 0) {
        sendStatus.value = false;
        snedTime.value = 60;
        clearInterval(timer.value);
      }
    }, 1000);
  } catch (e) {
    sendStatus.value = false;
    console.log("error msg:", e);
  }
};
// 登录
const password = ref("");
const loginStatus = ref(false);
const login = async () => {
  const user = useUserStore();
  // 短信登录
  if (tabActive.value === 0) {
    if (!mobile.value) {
      return ElMessage.warning("请输入手机号");
    }
    // 正则表达式
    if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
      return ElMessage.warning("请输入正确的手机号");
    }
    if (!smsCode.value) {
      return ElMessage.warning("请输入短信验证码");
    }
    // 验证短信验证码，数字4-6位
    if (!/^\d{4,6}$/.test(smsCode.value)) {
      return ElMessage.warning("短信验证码格式不正确，请输入4-6位数字");
    }
    if (!checked.value) {
      return ElMessage.warning("请勾选同意协议");
    }
    if (loginStatus.value) return;
    loginStatus.value = true;
    try {
      // 使用新的登录或注册接口
      const { data } = await loginOrRegisterAPI({
        clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
        grantType: "sms",
        phonenumber: mobile.value,
        smsCode: smsCode.value,
        userType: 'buyer',
      });
      console.log(data);
      if (data.token || data.access_token) {
        ElMessage.success("登录成功");
        // 优先使用新格式的token，兼容旧格式的access_token
        const token = data.token || data.access_token;
        await user.setToken(token);
        
        // 保存完整的用户信息
        const userInfo = {
          userId: data.userId,
          username: data.username,
          nickname: data.nickname || data.username,
          userType: data.userType,
          companyId: data.companyId,
          companyName: data.companyName
        };
        await user.setUserInfo(userInfo);
        
        // 获取店铺信息
        try {
          await user.getShopInfo();
        } catch (error) {
          console.error('获取店铺信息失败:', error);
        }
        
        // 确保用户信息已正确设置后再跳转
        await nextTick();
        
        // 检查是否有redirect参数，如果有则跳转到指定页面，否则跳转到首页
        const redirectPath = route.query.redirect as string;
        if (redirectPath) {
          await router.push(redirectPath);
        } else {
          await router.push("/");
        }
      }
    } catch (e) {
      console.log("error msg:", e);
      ElMessage.error("登录失败");
    } finally {
      loginStatus.value = false;
    }
  }
  // 账号密码登录
  if (tabActive.value === 1) {
    if (!mobile.value) {
      return ElMessage.warning("请输入手机号");
    }
    if (!/^1[3-9]\d{9}$/.test(mobile.value)) {
      return ElMessage.warning("请输入正确的手机号");
    }
    if (!password.value) {
      return ElMessage.warning("请输入密码");
    }
    if (!checked.value) {
      return ElMessage.warning("请勾选同意协议");
    }
    try {
      if (loginStatus.value) return;
      loginStatus.value = true;
      // 使用新的登录或注册接口进行密码登录
      const { data } = await loginOrRegisterAPI({
        clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
        grantType: "password",
        username: mobile.value,
        password: password.value,
        userType: 'buyer',
      });
      console.log(data);
      if (data.token || data.access_token) {
        ElMessage.success("登录成功");
        // 优先使用新格式的token，兼容旧格式的access_token
        const token = data.token || data.access_token;
        await user.setToken(token);
        
        // 保存完整的用户信息
        const userInfo = {
          userId: data.userId,
          username: data.username,
          nickname: data.nickname || data.username,
          userType: data.userType,
          companyId: data.companyId,
          companyName: data.companyName
        };
        await user.setUserInfo(userInfo);
        
        // 获取店铺信息
        try {
          await user.getShopInfo();
        } catch (error) {
          console.error('获取店铺信息失败:', error);
        }
        
        // 检查是否有redirect参数，如果有则跳转到指定页面，否则跳转到首页
        const redirectPath = route.query.redirect as string;
        if (redirectPath) {
          await router.push(redirectPath);
        } else {
          await router.push("/");
        }
      }
    } catch (e) {
      console.log("error msg:", e);
      ElMessage.error("登录失败");
    } finally {
      loginStatus.value = false;
    }
  }
};
// 找回密码
const resetPwdFN = async () => {
  if (!mobile.value) {
    return ElMessage.warning("请输入手机号");
  }
  if (!smsCode.value) {
    return ElMessage.warning("请输入短信验证码");
  }
  // 验证短信验证码格式，4-6位数字
  if (!/^\d{4,6}$/.test(smsCode.value)) {
    return ElMessage.warning("短信验证码格式不正确，请输入4-6位数字");
  }
  if (!password.value) {
    return ElMessage.warning("请输入新密码");
  }
  loginStatus.value = true;
  try {
    const data = await resetPwd({
      mobile: mobile.value,
      smsCode: smsCode.value,
      password: password.value,
    });
    ElMessage.success("找回密码成功");
    reserPwdStatus.value = false;
  } catch (e) {
    console.log("error msg:", e);
  } finally {
    loginStatus.value = false;
  }
};
// 获取协议等
const agreement = ref([]);
const getAgreementFn = async () => {
  try {
    const res = await getAgreement();
    agreement.value = res.data;
  } catch (err) {
    console.log(err);
  }
};
getAgreementFn();
const agreementList = computed(() => {
  return agreement.value.filter(
    (item) => item.type === 1 || item.type === 2 || item.type === 3 || item.type === 4
  );
});
</script>

<template>
  <BaseHeaderMenuWhite bg-color="white" :borderBottom="false" />
  <div class="login-view">
    <div class="login-form">
      <img class="form-title" src="~/assets/login-form-title.png" alt="" />
      <template v-if="!reserPwdStatus">
        <div class="login-form-content">
          <div class="form-left">
            <img class="logo" src="~/assets/web-logo-1.png" alt="" />
            <p class="tips">打开技能猴子App扫一扫即可登录</p>
            <div class="qr">
              <img src="~/assets/app-qrcode.png" alt="" />
            </div>
            <NuxtLink class="app-link" to="/appDownload">还没有技能猴子App？点击去下载</NuxtLink>
          </div>
          <div class="form-right">
            <p class="login-tab">
              <span :class="{ active: tabActive === 0 }" @click="tapTabActive(0)">手机号登录</span>
              <span :class="{ active: tabActive === 1 }" @click="tapTabActive(1)">密码登录</span>
            </p>
            <div class="form-item">
              <img src="~/assets/phone-icon.png" alt="" />
              <input v-model="mobile" type="number" placeholder="请输入手机号" />
            </div>
            <template v-if="tabActive === 0">
              <div class="form-item">
                <img src="~/assets/sms-icon.png" alt="" />
                <input type="text" v-model="smsCode" placeholder="请输入短信验证码" />
                <span @click="sendSms">{{
                  sendStatus ? `${snedTime} S` : "发送验证码"
                }}</span>
              </div>
            </template>
            <template v-if="tabActive === 1">
              <div class="form-item">
                <img src="~/assets/sms-icon.png" alt="" />
                <input v-model="password" type="password" placeholder="请输入密码" />
              </div>
              <p class="forgot-password" @click="reserPwdStatus = true">忘记密码？</p>
            </template>
            <el-button class="submit-btn" @click="login" color="#1dbf73" style="color: #fff !important"
              :loading="loginStatus" :disabled="loginStatus">登录</el-button>
            <p class="agreement" style="text-align: left; justify-content: flex-start;">
              <el-checkbox v-model="checked" />&nbsp; 我已阅读并同意&nbsp;
            </p>
            <p class="agreement" style="text-align: left; justify-content: flex-start;">
<NuxtLink v-for="item of agreementList"
                style="margin-right: 4px" :key="item.id" :to="`/agreement?id=${item.id}`" target="_blank">{{ item.title
                }}</NuxtLink>
            </p>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="reset-form-content">
          <img class="modal-close" @click="reserPwdStatus = false" src="~/assets/modal-close.png" alt="" />
          <p class="modal-title">
            <img src="~/assets/modal-back.png" alt="" @click="reserPwdStatus = false" /><span>找回密码</span>
          </p>
          <div class="form">
            <div class="form-item" style="width: 296px">
              <img src="~/assets/phone-icon.png" alt="" />
              <input v-model="mobile" type="text" placeholder="请输入手机号" />
            </div>
            <div class="form-item" style="width: 296px">
              <img src="~/assets/sms-icon.png" alt="" />
              <input v-model="smsCode" type="text" placeholder="请输入短信验证码" />
              <span @click="sendSms">{{
                sendStatus ? `${snedTime} S` : "发送验证码"
              }}</span>
            </div>
            <div class="form-item" style="width: 296px">
              <img src="~/assets/pwd-icon.png" alt="" />
              <input v-model="password" type="password" placeholder="请输入新密码" />
            </div>
            <div class="submit-btn" style="margin-top: 24px" @click="resetPwdFN">
              找回密码
            </div>
            <p class="to-login" @click="reserPwdStatus = false">直接登录</p>
          </div>
        </div>
      </template>
    </div>
    <div class="web-footer">
      <p>有声探网络科技有限公司  |  中国(合肥)高新区望江西路888号</p>
      <p>©2022 备案号：皖ICP备17049047号-6沪公网安备 31010502005484号</p>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-view {
  padding-top: 80px;
  min-height: 100vh;
  box-sizing: border-box;
  background: url("~/assets/login-bg.png") no-repeat;
  background-size: cover;
  background-position: center;
  position: relative;

  @media (max-width: 768px) {
    padding-top: 60px;
    background-size: cover;
  }
}

.login-form {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 80px 20px 0;
  display: flex;
  flex-direction: column;
  align-items: center;

  @media (max-width: 768px) {
    padding: 40px 16px 0;
  }

  @media (max-width: 480px) {
    padding: 20px 12px 0;
  }
}

.form-title {
  width: 100%;
  max-width: 400px;
  height: auto;
  margin-bottom: 48px;

  @media (max-width: 768px) {
    max-width: 300px;
    margin-bottom: 32px;
  }

  @media (max-width: 480px) {
    max-width: 250px;
    margin-bottom: 24px;
  }
}

.login-form-content {
  background: #ffffff;
  border-radius: 16px;
  width: 100%;
  display: flex;
  overflow: hidden;

  @media (max-width: 768px) {
    flex-direction: column;
    border-radius: 12px;
  }
}

.reset-form-content {
  background: #ffffff;
  border-radius: 16px;
  width: 100%;
  max-width: 380px;
  display: flex;
  position: relative;
  padding: 42px 42px 0;
  flex-direction: column;
  box-sizing: border-box;

  @media (max-width: 480px) {
    max-width: 100%;
    padding: 32px 24px 0;
    border-radius: 12px;
  }
}

.form-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 46px 20px;
  border-right: 1px solid rgba(25, 30, 40, 0.12);

  @media (max-width: 768px) {
    border-right: none;
    border-bottom: 1px solid rgba(25, 30, 40, 0.12);
    padding: 32px 20px;
  }

  @media (max-width: 480px) {
    padding: 24px 16px;
  }

  .logo {
    width: 118px;
    height: auto;
    margin-bottom: 32px;

    @media (max-width: 480px) {
      width: 100px;
      margin-bottom: 24px;
    }
  }

  .tips {
    color: #191e28;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;

    @media (max-width: 480px) {
      font-size: 14px;
      margin-bottom: 16px;
    }
  }

  .qr {
    box-shadow: 0px 4px 24px 0px rgba(3, 10, 26, 0.06);
    border-radius: 12px;
    border: 1px solid #edeff4;
    background: #ffffff;
    width: 160px;
    height: 160px;
    margin-bottom: 24px;
    overflow: hidden;

    @media (max-width: 480px) {
      width: 140px;
      height: 140px;
      margin-bottom: 20px;
    }

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .app-link {
    color: #01977f;
    text-decoration: none;
    text-align: center;
    font-size: 14px;

    @media (max-width: 480px) {
      font-size: 12px;
    }
  }
}

.form-right {
  flex: 1;
  padding: 48px 20px;
  display: flex;
  align-items: center;
  flex-direction: column;

  @media (max-width: 768px) {
    padding: 32px 20px;
  }

  @media (max-width: 480px) {
    padding: 24px 16px;
  }
}

.login-tab {
  margin-bottom: 34px;
  display: flex;
  justify-content: center;

  @media (max-width: 480px) {
    margin-bottom: 24px;
  }

  span {
    color: rgba(25, 30, 40, 0.36);
    font-size: 16px;
    cursor: pointer;

    @media (max-width: 480px) {
      font-size: 14px;
    }

    &:first-child {
      margin-right: 50px;

      @media (max-width: 480px) {
        margin-right: 30px;
      }
    }

    &.active {
      color: #191e28;
      position: relative;

      &::after {
        content: "";
        position: absolute;
        bottom: -8px;
        left: 50%;
        width: 48px;
        height: 2px;
        margin-left: -24px;
        background: #01977f;

        @media (max-width: 480px) {
          width: 36px;
          margin-left: -18px;
        }
      }
    }
  }
}

.form-item {
  display: flex;
  align-items: center;
  border-radius: 8px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  width: 100%;
  max-width: 304px;
  height: 48px;
  margin-bottom: 16px;
  padding: 0 12px;
  box-sizing: border-box;

  @media (max-width: 480px) {
    max-width: 100%;
    height: 44px;
    padding: 0 10px;
  }

  img {
    width: 18px;
    height: 18px;
    flex-shrink: 0;

    @media (max-width: 480px) {
      width: 16px;
      height: 16px;
    }
  }

  input {
    flex: 1;
    height: 100%;
    border: none;
    outline: none;
    user-select: none;
    padding-left: 12px;
    font-size: 14px;

    @media (max-width: 480px) {
      padding-left: 10px;
      font-size: 13px;
    }
  }

  span {
    color: #1dbf73;
    cursor: pointer;
    font-size: 14px;
    white-space: nowrap;

    @media (max-width: 480px) {
      font-size: 12px;
    }
  }
}

.forgot-password {
  color: #1dbf73;
  text-align: right;
  width: 100%;
  max-width: 304px;
  padding-right: 0;
  box-sizing: border-box;
  margin: -10px 0 -6px 0;
  cursor: pointer;
  font-size: 14px;

  @media (max-width: 480px) {
    font-size: 12px;
    max-width: 100%;
  }
}

.submit-btn {
  width: 100%;
  max-width: 304px;
  height: 48px;
  background: #1dbf73;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  margin-top: 16px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;

  @media (max-width: 480px) {
    max-width: 100%;
    height: 44px;
    font-size: 14px;
  }
}

.agreement {
  margin-top: 8px;
  font-size: 12px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  color: rgba(25, 30, 40, 0.32);
  max-width: 304px;
  text-align: left;
  line-height: 1.4;

  @media (max-width: 480px) {
    max-width: 100%;
    font-size: 11px;
    flex-wrap: wrap;
  }

  a {
    text-decoration: none;
    color: rgba(29, 191, 115, 1);
    cursor: pointer;
  }
}

.to-seller {
  color: #019a81;
  font-size: 16px;
  font-weight: bold;
  display: flex;
  align-items: center;
  text-decoration: none;
  margin-top: 16px;

  @media (max-width: 480px) {
    font-size: 14px;
    margin-top: 12px;
  }

  .icon {
    position: relative;
    top: 1px;
  }
}

.modal-close {
  position: absolute;
  top: 40px;
  right: 40px;
  width: 16px;
  height: 16px;
  cursor: pointer;

  @media (max-width: 480px) {
    top: 32px;
    right: 24px;
    width: 14px;
    height: 14px;
  }
}

.modal-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;

  @media (max-width: 480px) {
    margin-bottom: 20px;
  }

  img {
    width: 20px;
    height: 20px;
    margin-right: 4px;
    cursor: pointer;

    @media (max-width: 480px) {
      width: 18px;
      height: 18px;
    }
  }

  span {
    color: #191e28;
    font-size: 18px;
    font-weight: bold;

    @media (max-width: 480px) {
      font-size: 16px;
    }
  }
}

.to-login {
  text-align: center;
  color: #019a81;
  padding: 24px 0;
  cursor: pointer;
  font-size: 14px;

  @media (max-width: 480px) {
    padding: 20px 0;
    font-size: 13px;
  }
}

.web-footer {
  position: relative;
  margin-top: 60px;
  padding: 0 20px 48px;
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: rgba(25, 30, 40, 0.36);
  box-sizing: border-box;

  @media (max-width: 768px) {
    margin-top: 40px;
    padding: 0 16px 32px;
    font-size: 11px;
  }

  @media (max-width: 480px) {
    margin-top: 32px;
    padding: 0 12px 24px;
    font-size: 10px;
  }

  p:nth-child(1) {
    margin-bottom: 10px;

    @media (max-width: 480px) {
      margin-bottom: 8px;
    }
  }
}

// 针对找回密码表单的特殊样式
.reset-form-content .form-item {
  width: 100%;
  max-width: 296px;

  @media (max-width: 480px) {
    max-width: 100%;
  }
}

.reset-form-content .submit-btn {
  max-width: 296px;

  @media (max-width: 480px) {
    max-width: 100%;
  }
}

// 平板适配
@media (min-width: 769px) and (max-width: 1024px) {
  .login-form {
    max-width: 700px;
    padding: 60px 24px 0;
  }

  .form-title {
    max-width: 350px;
  }

  .form-left {
    padding: 40px 16px;
  }

  .form-right {
    padding: 40px 16px;
  }
}

// 大屏幕适配
@media (min-width: 1200px) {
  .login-form {
    max-width: 900px;
  }

  .form-title {
    max-width: 450px;
  }
}
</style>
<style>
.agreement .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: rgba(29, 191, 115, 1);
}
</style>
